<template>
    <div class="cart-container">
        <h1>购物车</h1>
        <ul>
            <li v-for="item in cart.items" :key="item.id">
                {{ item.name }}---{{ item.quantity }} --- ￥{{ item.price }}
                <button @click="removeCartForm(item.id)">移除</button>
            </li>
        </ul>
        <div class="total-price">
            总价：￥{{ totalPrice }}
        </div>
        <button @click="clearCart()">清空购物车</button>
        <div class="add-item-form">
            <h3>添加商品</h3>
            <label for="itemName">商品名称：</label>
            <input v-model="newItemName"  type="text" placeholder="商品名称" id="itemName">
            <label for="itemNum">商品数量:</label>
            <input v-model="newItemQuantity" type="number" placeholder="商品数量" id="itemNum">
            <label for="itemPrice">商品价格：</label>
            <input v-model="newItemPrice" type="number" placeholder="商品价格" id="itemPrice">
            <button @click="addToCart">添加到购物车</button>
        </div>
    </div>
</template>
<script setup>
import { ref,computed } from 'vue';
import {useCartStore} from '../store/cartStore.js'

const cart=useCartStore()


const newItemName = ref('')
const newItemQuantity = ref(1)
const newItemPrice = ref(0)

// 添加商品
const addToCart =() =>{
    const newItem={
        id:Date.now(), //时间戳
        name:newItemName.value,
        quantity:newItemQuantity.value,
        price:newItemPrice.value
    }
    cart.addItem(newItem)
    newItemName.value=''
    newItemQuantity.value=1
    newItemPrice.value=0
}
// 移除商品
const removeCartForm=(itemID)=>{
    cart.removeItem(itemID)
}
// 清空购物车
const clearCart=()=>{
    cart.clearCart()
}
// 总价计算
const totalPrice = computed(()=>{
    return cart.items.reduce((total,item)=> total + item.price*item.quantity,0)
})


</script>

<style lang="less">
body{
    margin: 20px;
    background-color: #f4f4f4;
 .cart-container{
    background-color: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, .1) ;
    max-width: 1000px;
    margin: 0 auto;
 }
}
h1,h2,h3{
    color: #333;
}

ul{
    list-style-type: none;
    padding: 0;

    li{
    list-style: none;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;
    border-bottom: 1px solid #ddd;
}
}

li:last-child{
    border-bottom: none;
}
button{
    background-color: #b42b2b;
    color: #fff;
    border: none;
    padding: 10px 20px;
    border-radius: 6px;
    cursor: pointer;
    transition: .3s;
}
button:hover{
    background-color: #791616;
}
.total-price{
    font-weight: 600;
    margin: 10px 0;

}
.add-item-form{
    margin-top: 20px;
}
.add-item-form input{
    width: 130px;
    margin-right: 10px;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
}





</style>